<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css">
		#c{
			border:1px solid red;
		}
	</style>
</head>
<body>
	<canvas id="c" width="1000" height="600" mydata="abc"></canvas>


	<script type="text/javascript">

		//  ||  Enter键  shift+ Enter键 上面的按键
		
		// 或||  两边只要有一个正确，结论就正确
		// 与&&  两边必须都正确，结论才正确
		
		
		// var b1 = new Ball(200,200,50,'c');
		// b1.draw();
		var ctx = c.getContext('2d');
		// setInterval(function () {
		// 	ctx.clearRect(0,0,1000,600);
		// 	b1.draw();
		// },30);

		//for循环创建50个球  
		var balls = [];
		for(var i=0;i<50;i++){
			var circle = new Ball(random(50,1000),random(50,600),random(20,50),0,2*Math.PI,false);
			balls.push(circle);
			circle.draw();
		}
		// console.log(balls);

		setInterval(function () {
			ctx.clearRect(0,0,1000,600);
			// 重绘小球
			for(var k=0;k<balls.length;k++){
				balls[k].draw();
			}
		},30);


		function random(min,max) {
			return Math.random()*(max-min)+min;
		}



		function Ball(x,y,r,id) {
			// this.x = x||random(10,1000);
			this.x = x;
			this.y = y;
			this.r = r;
			// 优化：如果程序员不传入id这个参数，我们给他默认值c
			this.id = id||'c';//  'c'||id
			this.speed = {
				dx: random(-8,8),
				dy: random(-4,4)
			}
			this.draw = function () {
				var c = document.getElementById(this.id);
				var ctx = c.getContext('2d');
				ctx.beginPath();
				ctx.arc(this.x,this.y,this.r,0,2*Math.PI,false);
				ctx.stroke();
				ctx.closePath();
				//球下一次的位置会发生改变
				this.x += this.speed.dx;
				if(this.x>c.width||this.x<0){
					this.speed.dx = -this.speed.dx;
				}
				this.y +=this.speed.dy;
				if(this.y>c.height||this.y<0){
					this.speed.dy = -this.speed.dy;
				}
			}
		}
	</script>
</body>
</html>